<template>
  <div class="scan">
    <div id="bcid">
      <div style="height: 40%"></div>
      <p class="tip">...载入中...</p>
    </div>
    <div class="goBack">
      <el-button
        type="primary"
        icon="el-icon-caret-left"
        circle
        @click="goBack()"
      ></el-button>
    </div>
  </div>
</template>

<script type='text/ecmascript-6'>
/**
 * h5+ 扫码功能实现
 */
let scan = null
export default {
  data() {
    return {
      equipment: {}
    }
  },
  mounted() {
    this.startRecognize()
  },
  beforeDestroy() {
    this.closeScan()
  },
  methods: {
    // 创建扫描控件
    startRecognize() {
      // 边框属性
      const styles = {
        frameColor: '#f8f8f8',
        scanbarColor: '#f8f8f8',
        background: '#000'
      }

      var filter = null // 扫码格式 空为全类型，不能省略

      if (!window.plus) return
      scan = new plus.barcode.Barcode('bcid', filter, styles)

      // 扫码成功回调
      scan.onmarked = (type, result, file) => {
        switch (type) {
          case plus.barcode.QR:
            type = 'QR'
            break
          case plus.barcode.EAN13:
            type = 'EAN13'
            break
          case plus.barcode.EAN8:
            type = 'EAN8'
            break
          default:
            type = '其它' + type
            break
        }

        // 获得 code
        result = result.replace(/\n/g, '')

        if (result) {
          console.log(result)

          // 先发起请求判断是否存在
          this.$http
            .get('utils/get-equipment', {
              params: {
                id: result
              }
            })
            .then(res => {
              this.equipment = res.data.data
              console.log(this.equipment)

              setTimeout(() => {
                this.$router.push({
                  name: 'callUp',
                  params: {
                    equipment: this.equipment
                  }
                })
              }, 200)
            })
            .catch(() => {
              setTimeout(() => {
                this.$router.push('/')
              }, 300)
              alert('错误二维码')
            })
        }
      }

      this.startScan()
    },
    // 开始扫描
    startScan() {
      if (!window.plus) return
      scan.start()
    },
    // 关闭扫描
    cancelScan() {
      if (!window.plus) return
      scan.cancel()
    },
    // 关闭条码识别控件
    closeScan() {
      if (!window.plus) return
      scan.close()
    },
    // 销毁前关闭摄像头
    beforeDestroy() {
      if (scan) {
        // 关闭扫描控件
        scan.close()
      }
    },
    goBack() {
      this.$router.push('/')
    }
  }
}
</script>

<style lang="less">
.scan {
  height: 100%;
  #bcid {
    width: 100%;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    text-align: center;
    color: #fff;
    background: #ccc;
  }
}

.goBack {
  z-index: 10;
  position: fixed;
  top: 90%;
  left: 80%;
}
</style>
